<template>
  <div>
    <el-row v-if="canEditSku">
      <el-col>
        <el-button :disabled="skuFormData.regualrList.length >= maxSkuCount" type="primary" icon="el-icon-plus" @click="addSku">添加商品规格</el-button>
      </el-col>
    </el-row>
    <el-form v-show="canEditSku" ref="form" :model="skuFormData" label-position="right" label-width="110px">
      <el-row v-for="(sku, skuIndex) in skuFormData.regualrList" :key="skuIndex" class="sku-item">
        <el-col :span="24">
          <el-form-item
            :rules="[
              { validator: validSku , trigger: 'change'}
            ]"
            :label="'规格名 '+ (skuIndex + 1) + ':'"
            :prop="'regualrList.' + skuIndex + '.name'"
            style="padding-bottom: 5px"
          >
            <el-col :span="24">
              <el-input v-model="sku.name" :disabled="!canEditSku" placeholder="请输入规格名，例如：颜色、尺寸、型号" maxlength="10" style="max-width: 300px;" />
              <el-button v-if="canEditSku" :disabled="sku.valueList.length >= maxSpecCount" style="margin-left: 15px;" type="primary" icon="el-icon-plus" @click="addSpec(skuIndex)">添加规格值</el-button>
              <el-button v-if="canEditSku" style="margin-left: 15px;" type="danger" icon="el-icon-delete" @click="deleteSku(skuIndex)">删除</el-button>
            </el-col>
          </el-form-item>
        </el-col>
        <el-col :offset="1" :span="23">
          <el-form-item
            v-for="(spec, specIndex) in sku.valueList"
            :key="specIndex"
            :label="'规格值 '+ (specIndex + 1) + ':'"
            :rules="[
              { validator: validSpec , trigger: 'change'}
            ]"
            :prop="'regualrList.' + skuIndex + '.valueList.' + specIndex + '.value'"
            style="margin-top: 15px;padding-bottom: 5px"
          >
            <el-col :span="24">
              <el-input v-model="spec.value" :disabled="!canEditSku" placeholder="请输入规格值，例如：红色、M号、G25" maxlength="10" style="max-width: 300px;" />
              <el-button v-if="canEditSku && sku.valueList.length > 1" style="margin-left: 15px;" type="danger" icon="el-icon-delete" @click="deleteSpec(skuIndex, specIndex)">删除</el-button>
            </el-col>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <div v-if="skuTableData != null">
      <div style="width: 100%; margin-top: 20px">
        <el-radio-group v-model="isRowSpan">
          <el-radio-button :label="true">SKU表格合并行显示</el-radio-button>
          <el-radio-button :label="false">SKU表格独立行显示</el-radio-button>
        </el-radio-group>
      </div>
      <el-table
        :data="skuTableData"
        :span-method="skuSpanRow"
        border
        style="width: 100%; margin-top: 20px"
      >
        <el-table-column
          v-for="(sku, skuIndex) in skuFormData.regualrList"
          :key="skuIndex"
          prop="id"
          :label="sku.name"
          min-width="120"
          align="center"
          :resizable="false"
        >
          <template slot-scope="scope">
            {{ scope.row.regualrs[skuIndex].value }}
          </template>
        </el-table-column>
        <el-table-column
          prop="name"
          label="商品图片"
          align="center"
          :resizable="false"
          width="90"
        >
          <template slot-scope="scope">
            <sku-img v-model="scope.row.picture" />
          </template>
        </el-table-column>
        <el-table-column
          prop="amount1"
          label="零售价格（元）"
          align="center"
          min-width="120"
          :resizable="false"
        >
          <template slot-scope="scope">
            <el-input-number
              v-model="scope.row.salePrice"
              size="small"
              style="width: 100%;"
              :min="0"
              :max="100000"
              :controls="false"
              :precision="2"
              placeholder="单位元"
              @change="fixNumber($event, scope.$index, 'salePrice')"
            />
          </template>
        </el-table-column>
        <el-table-column
          prop="amount2"
          label="库存"
          align="center"
          min-width="120"
          :resizable="false"
        >
          <template slot-scope="scope">
            <el-input-number
              v-model="scope.row.stock"
              size="small"
              style="width: 100%;"
              :min="0"
              :max="100000"
              :controls="false"
              :precision="2"
              placeholder="单位元"
              @change="fixNumber($event, scope.$index, 'stock')"
            />
          </template>
        </el-table-column>
        <el-table-column
          v-if="leaseGoods"
          prop="amount3"
          label="押金（元）"
          align="center"
          min-width="120"
          :resizable="false"
        >
          <template slot-scope="scope">
            <el-input-number
              v-model="scope.row.deposit"
              size="small"
              style="width: 100%;"
              :min="0"
              :max="100000"
              :controls="false"
              :precision="2"
              placeholder="单位元"
              @change="fixNumber($event, scope.$index, 'deposit')"
            />
          </template>
        </el-table-column>
        <!--        <el-table-column
          prop="amount3"
          label="商品重量（克）"
          align="center"
          min-width="120"
          :resizable="false"
        >
          <template slot-scope="scope">
            <el-input-number
              v-model="scope.row.weight"
              size="small"
              style="width: 100%;"
              :min="0"
              :max="1000000"
              :controls="false"
              placeholder="单位克"
              @change="fixNumber($event, scope.$index, 'weight')"
            />
          </template>
        </el-table-column>-->
      </el-table>
    </div>
  </div>
</template>

<script>
import { Message } from 'element-ui'
import { guid } from '@/utils/index'
import SkuImg from '../SkuImg/index'
export default {
  name: 'GoodsStoreSku',
  components: { SkuImg },
  props: {
    leaseGoods: {
      type: Boolean,
      default: false
    },
    canEditSku: {
      type: Boolean,
      default: true
    },
    skuFormData: {
      type: Object,
      default() {
        return {
          regualrList: []
        }
      }
    },
    regualrCombo: {
      type: Array,
      default() {
        return []
      }
    }
  },
  data() {
    return {
      validSku: (rule, value, callback) => {
        if (value === undefined || value == null || value.trim().length <= 0) {
          Message.closeAll()
          Message.error('商品规格名不能为空')
          callback(new Error('请输入规格名'))
          return
        }
        let count = 0
        this.skuFormData.regualrList.forEach(sku => {
          if (sku.name === value) {
            count++
          }
        })
        if (count > 1) {
          Message.closeAll()
          Message.error('商品规格名【' + value + '】重复，请修改')
          callback(new Error('规格名重复，请修改'))
          return
        }
        callback()
      },
      validSpec: (rule, value, callback) => {
        if (value === undefined || value == null || value.trim().length <= 0) {
          Message.closeAll()
          Message.error('商品规格值不能为空')
          callback(new Error('请输入规格值'))
          return
        }
        let count = 0
        this.skuFormData.regualrList[rule.fullField.split('.')[1]].valueList.forEach(spec => {
          if (spec.value === value) {
            count++
          }
        })
        if (count > 1) {
          Message.closeAll()
          Message.error('商品规格值【' + value + '】重复，请修改')
          callback(new Error('规格值重复，请修改'))
          return
        }
        callback()
      },
      // 最多允许添加几个SKU规格
      maxSkuCount: 4,
      // 每个规格最多允许添加几个规格值
      maxSpecCount: 5,
      isRowSpan: true,
      isValidate: false,
      isFillData: false,
      skuTableData: []
    }
  },
  watch: {
    skuFormData: {
      handler(val, oldVal) {
        this.createTable()
      },
      deep: true
    },
    regualrCombo: {
      handler(val, oldVal) {
        this.createTable()
      },
      deep: true
    }
  },
  created() {
    this.createTable()
  },
  methods: {
    validate() {
      if (this.skuFormData.regualrList.length <= 0) {
        this.isValidate = false
        Message.closeAll()
        Message.error('请至少添加一个商品规格')
        return false
      }
      this.$refs.form.validate((valid) => {
        this.isValidate = valid
      })
      return this.isValidate
    },
    fixNumber(val, index, key) {
      if (val === undefined) {
        this.skuTableData[index][key] = -100000
      }
      this.$forceUpdate()
    },
    addSku() {
      this.skuFormData.regualrList.push({
        _key: guid(),
        specInfoId: -1,
        name: null,
        valueList: [{
          _key: guid(),
          specId: -1,
          value: null
        }]
      })
    },
    deleteSku(skuIndex) {
      this.skuFormData.regualrList.splice(skuIndex, 1)
    },
    addSpec(skuIndex) {
      this.skuFormData.regualrList[skuIndex].valueList.push({
        _key: guid(),
        specId: -1,
        value: null
      })
    },
    deleteSpec(skuIndex, specIndex) {
      this.skuFormData.regualrList[skuIndex].valueList.splice(specIndex, 1)
    },
    skuSpanRow({ row, column, rowIndex, columnIndex }) {
      if (this.isRowSpan && columnIndex < this.skuFormData.regualrList.length - 1) {
        if (rowIndex === row.regualrs[columnIndex]._start) {
          return {
            rowspan: row.regualrs[columnIndex]._end - row.regualrs[columnIndex]._start + 1,
            colspan: 1
          }
        } else if (rowIndex > row.regualrs[columnIndex]._start && rowIndex <= row.regualrs[columnIndex]._end) {
          return {
            rowspan: 0,
            colspan: 1
          }
        }
      }
    },
    createTable() {
      const vm = this
      try {
        if (vm.skuFormData.regualrList.length <= 0) {
          vm.skuTableData = null
          vm.fillTableData()
          vm.emitSkuData()
          return
        }
        let result = Array.prototype.reduce.call(vm.skuFormData.regualrList, function(a, b) {
          var ret = []
          a.forEach(function(aa) {
            b.valueList.forEach(function(bb) {
              if (b._key === undefined) {
                b._key = guid()
              }
              if (bb._key === undefined) {
                bb._key = guid()
              }
              const obj = {
                _key: b._key + '#' + bb._key,
                name: b.name,
                value: bb.value
              }
              ret.push(aa.concat([obj]))
            })
          })
          return ret
        }, [[]])

        result = result.map(item => {
          const arr = []
          item.forEach(e => {
            arr.push(e._key)
          })
          const _key = arr.join('|')
          if (vm.skuTableData && vm.skuTableData.length > 0) {
            const oldItem = vm.$XEUtils.find(vm.skuTableData, item => item._key === _key)
            if (oldItem) {
              const res = {
                _key: _key,
                regualrs: item,
                picture: oldItem.picture,
                cost: oldItem.cost,
                orginalPrice: oldItem.orginalPrice,
                weight: oldItem.weight,
                deposit: oldItem.deposit
              }
              return res
            }
          }
          const res = {
            _key: _key,
            regualrs: item,
            picture: null,
            cost: 0,
            orginalPrice: 0,
            weight: 0,
            deposit: 0
          }
          return res
        })

        result = result.map(item => {
          const arr = []
          item.regualrs.forEach(e => {
            arr.push(e._key)
            const _key = arr.join('|')
            e._start = vm.$XEUtils.findIndexOf(result, item2 => vm.$XEUtils.startsWith(item2._key, _key))
            e._end = vm.$XEUtils.findLastIndexOf(result, item2 => vm.$XEUtils.startsWith(item2._key, _key))
          })
          return item
        })
        // console.log(result)
        vm.skuTableData = result
        vm.fillTableData()
        vm.emitSkuData()
      } catch (e) {
        vm.skuTableData = []
        vm.fillTableData()
        vm.emitSkuData()
      }
    },
    emitSkuData() {
      if (this.skuTableData == null || this.skuTableData.length <= 0) {
        this.$emit('change', null, this.skuFormData)
        return
      }
      const regualr = this.$XEUtils.clone(this.skuTableData, true)
      regualr.forEach(sku => {
        sku.regualrs.forEach(spec => {
          delete spec._key
          delete spec._start
          delete spec._end
        })
        delete sku._key
        if (!this.leaseGoods) {
          sku.deposit = 0
        }
      })
      this.$emit('change', regualr, this.skuFormData)
      return
    },
    fillTableData() {
      const vm = this

      if (!vm.regualrCombo || vm.regualrCombo.length <= 0 || !vm.skuTableData || vm.skuTableData.length <= 0) {
        return
      }

      if (vm.isFillData) {
        return
      }

      vm.isFillData = true

      console.log('填充数据...')

      vm.skuTableData.forEach(sku => {
        const arr1 = []
        sku.regualrs.forEach(spec => {
          arr1.push(spec.name + '：' + spec.value)
        })
        const key1 = arr1.join('；')
        vm.regualrCombo.forEach(item => {
          const arr2 = []
          item.regualrs.forEach(item2 => {
            arr2.push(item2.name + '：' + item2.value)
          })
          const key2 = arr2.join('；')
          if (key1 === key2) {
            sku.picture = item.picture
            sku.cost = item.cost
            sku.weight = item.weight
            sku.productId = item.productId
            sku.orginalPrice = item.orginalPrice
            sku.deposit = item.deposit
            sku.regualrs.forEach((item3, index) => {
              item3.specId = item.regualrs[index].specId
            })
          }
        })
      })

      // console.log(vm.skuTableData)
    }
  }
}
</script>

<style scoped lang="scss">
.sku-item {
  margin-top: 15px;
  padding: 15px;
  border: 1px solid #eeeeee;
}
</style>
